<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;

use Admin\Data\Common;
use Admin\Data\Config;
use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsCommonContent;

class GoodsCommonContentManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加商品通用内容
     * @param array $data
     * @return GoodsCommonContent
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsCommonContent(array $data)
    {
        $data['classIdStr'] = ','.implode(',', $data['classId']).',';
        unset($data['classId']);

        $content = new GoodsCommonContent();
        $content->valuesSet($data);

        $this->entityManager->persist($content);
        $this->entityManager->flush();

        return $content;
    }

    /**
     * 编辑商品通用内容
     * @param array $data
     * @param GoodsCommonContent $goodsCommonContent
     * @return GoodsCommonContent
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoodsCommonContent(array $data, GoodsCommonContent $goodsCommonContent)
    {
        $data['classIdStr'] = ','.implode(',', $data['classId']).',';
        unset($data['classId']);

        $goodsCommonContent->valuesSet($data);
        $this->entityManager->flush();

        return $goodsCommonContent;
    }

    /**
     * 删除商品通用内容
     * @param GoodsCommonContent $goodsCommonContent
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoodsCommonContent(GoodsCommonContent $goodsCommonContent)
    {
        $imageList = Common::bodyImageArray($goodsCommonContent->getContentBody());

        $this->entityManager->remove($goodsCommonContent);
        $this->entityManager->flush();

        if ($imageList) foreach ($imageList as $imageValue) {
            if (stripos($imageValue, 'http') !== false) continue;
            @unlink(Config::GOODS_COMMON_IMAGE_PATH . basename($imageValue));
        }

        return true;
    }
}